<?php
namespace app\api\model\foodcash;

use app\api\model\Setting;
use think\facade\Cache;
use hema\Helper;

/**
 * 购物车管理
 */
class Cart
{
    public $error = '';	//错误信息
    private $user_id;	//用户id
	private $shop_id;	//门店id
    private $cart = [];	//购物车列表
    private $clear = false;	//是否清空购物车

    /**
     * 构造方法
     */
    public function __construct($user_id,$shop_id)
    {
        $this->user_id = $user_id;
		$this->shop_id = $shop_id;
        $this->cart = Cache::get('cart_foodcash_' . $user_id . '_' . $shop_id) ?: [];
    }
	
	/**
     * 获取购物车内容
     */
    public function getCart()
    {
		return $this->cart;
	}

    /**
     * 购物车列表
     */
    public function getList($order_mode = 0)
    {
        // 商品列表
        $goodsList = [];
        $goodsIds = array_unique(array_column($this->cart, 'goods_id'));
        foreach ((new Goods)->getListByIds($goodsIds) as $goods) {
            $goodsList[$goods['goods_id']] = $goods;
        }
        $pack_price = 0;//餐盒初始费
        $activity_price = 0;//优惠金额
        $min_price = 0;//外卖最低起送价
        $express_price = 0;//外卖配送费
        // 购物车商品列表
        $cartList = [];
        foreach ($this->cart as $key => $cart) {
            // 判断商品不存在则自动删除
            if (!isset($goodsList[$cart['goods_id']])) {
                $this->delete($cart['goods_id'], $cart['goods_sku_id']);
                continue;
            }
            $goods = clone $goodsList[$cart['goods_id']];
            // 商品sku信息
            $goods['goods_sku_id'] = $cart['goods_sku_id'];
            // 商品sku不存在则自动删除
            if (!$goods['goods_sku'] = $goods->getGoodsSku($cart['goods_sku_id'])) {
                $this->delete($cart['goods_id'], $cart['goods_sku_id']);
                continue;
            }
            // 判断商品是否下架
            if ($goods['goods_status']['value'] != 10) {
                $this->setError('很抱歉，商品 [' . $goods['goods_name'] . '] 已下架');
            }
            //计算餐盒费
			if($order_mode == 20 OR $order_mode == 30){
				if($goods['pack_price']>0){
					$pack_price = $pack_price + $goods['pack_price']*$cart['goods_num'];
				}
			}
			// 商品单价
			$goods['goods_price'] = $goods['goods_sku']['goods_price'];
			// 商品总价
			$goods['total_num'] = $cart['goods_num'];
			$goods['total_price'] = $total_price = bcmul($goods['goods_price'], $cart['goods_num'], 2);
            $cartList[] = $goods->hidden(['category', 'content', 'spec']);
        }
        //如果是外卖 +配送费用
		if($order_mode==20){
            //获取配送设置
            $delivery = Setting::getItem('delivery');
			$express_price = $delivery['delivery_price'];
			$min_price = $delivery['min_price'];			
		}
        // 商品总金额
        $orderTotalPrice = Helper::getArrayColumnSum($cartList, 'total_price');
        $order_pay_price = $orderTotalPrice;
        //餐盒费加入总价
		if($pack_price>0){
			$order_pay_price = $order_pay_price + $pack_price;
		}
		//优惠金额加入总价
		if($activity_price>0){
			$order_pay_price = $order_pay_price - $activity_price;
		}
		//外卖配送费加入总价
		if($express_price>0){
			$order_pay_price = $order_pay_price + $express_price;
		}
        return [
            'goods_list' => $cartList,                       // 商品列表
            'order_total_num' => $this->getTotalNum(),       // 商品总数量
            'order_total_price' => Helper::number2($orderTotalPrice),              // 商品总金额 (不含运费)
            'order_pay_price' => Helper::number2($order_pay_price),    // 实际支付金额
            'pack_price' => Helper::number2($pack_price),	// 餐盒费用
            'activity_price' => Helper::number2($activity_price),	//优惠费用费用
            'min_price' => Helper::number2($min_price),	// 起送价价
            'express_price' => Helper::number2($express_price),       // 配送费用
            'has_error' => $this->hasError(),
            'error_msg' => $this->getError(),
        ];
    }

    /**
     * 添加购物车
     */
    public function add($data)
    {
        // 购物车商品索引
        $index = $data['goods_id'] . '_' . $data['goods_sku_id'];
        // 商品信息
        $goods = Goods::detail($data['goods_id']);
        // 商品sku信息
        $goods['goods_sku'] = $goods->getGoodsSku($data['goods_sku_id']);
        // 判断商品是否下架
        if ($goods['goods_status']['value'] != 10) {
            $this->setError('很抱歉，该商品已下架');
            return false;
        }
        // 判断商品库存
        $cartGoodsNum = $data['goods_num'] + (isset($this->cart[$index]) ? $this->cart[$index]['goods_num'] : 0);
        $data['create_time'] = time();
        if (sizeof($this->cart) == 0) {
            $this->cart[$index] = $data;
            return true;
        }
        isset($this->cart[$index]) ? $this->cart[$index]['goods_num'] = $cartGoodsNum : $this->cart[$index] = $data;
        return true;
    }

    /**
     * 减少购物车中某商品数量
     */
    public function sub($data)
    {
        $index = $data['goods_id'] . '_' . $data['goods_sku_id'];
        if($this->cart[$index]['goods_num'] > 1 ){
            $this->cart[$index]['goods_num']--;
        }elseif($this->cart[$index]['goods_num'] == 1){
            unset($this->cart[$index]);
        }
    }

    /**
     * 删除购物车中指定商品
     */
    public function delete($data)
    {
        //为空是批量删除
        if(empty($data['goods_id'])){
            $indexArr = strpos($data['goods_sku_id'], ',') !== false ? explode(',', $data['goods_sku_id']) : [$data['goods_sku_id']];
            foreach ($indexArr as $index) {
                if (isset($this->cart[$index])) unset($this->cart[$index]);
            }
        }else{
            $index = $data['goods_id'] . '_' . $data['goods_sku_id'];
            if (isset($this->cart[$index])) unset($this->cart[$index]);
        }
    }

    /**
     * 获取当前用户购物车商品总数量
     */
    public function getTotalNum()
    {
        return array_sum(array_column($this->cart, 'goods_num'));
    }

    /**
     * 析构方法
     * 将cart数据保存到缓存文件
     */
    public function __destruct()
    {
        $this->clear !== true && Cache::set('cart_foodcash_' . $this->user_id . '_' . $this->shop_id, $this->cart, 86400);
    }

    /**
     * 清空当前用户购物车
     */
    public function clearAll()
    {
        $this->clear = true;
        Cache::delete('cart_foodcash_' . $this->user_id . '_' . $this->shop_id);
    }

    /**
     * 设置错误信息
     */
    private function setError($error)
    {
        empty($this->error) && $this->error = $error;
    }

    /**
     * 是否存在错误
     */
    private function hasError()
    {
        return !empty($this->error);
    }

    /**
     * 获取错误信息
     */
    public function getError()
    {
        return $this->error;
    }
}
